//
//  AddYourInfoViewController.m
//  us
//
//  Created by karry on 2025/4/1.
//

#import "AddYourInfoViewController.h"
#import "MainViewController.h"

#import "USDateAlertView.h"
#import "SceneDelegate.h"
@interface AddYourInfoViewController ()

@property (nonatomic, strong)UIButton *doneBtn;


@property (nonatomic, strong)NSDate *birthDate;

@end

@implementation AddYourInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self setupView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    self.nickTx.text = USUser.user.nickname?:@"";//第三方登录携带的用户名
 
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.nickTx becomeFirstResponder];
}

- (void)setupView {
    self.nickBgView.layer.borderColor = UIColor.clearColor.CGColor;
    self.sexBgView.layer.borderColor = UIColor.clearColor.CGColor;
    self.birthdayBgView.layer.borderColor = UIColor.clearColor.CGColor;
    
    [self.view addSubview:self.doneBtn];
    [self.doneBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(56);
        make.left.mas_equalTo(self.view.mas_safeAreaLayoutGuideLeft).mas_offset(32);
        make.right.mas_equalTo(self.view.mas_safeAreaLayoutGuideRight).mas_offset(-32);
        make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).mas_offset(-28);
    }];
    
    @weakify(self);
    
    [[self.nickTx.rac_textSignal distinctUntilChanged] subscribeNext:^(NSString * _Nullable text) {
        @strongify(self);
        // 限制最多10字符
        if (text.length > 10) {
            text = [text substringToIndex:10];
            self.nickTx.text = text;
        }
 
    }];
    
    
    RACSignal *nickValidSignal = [self.nickTx.rac_textSignal map:^id _Nullable(NSString * _Nullable text) {
        return @(text.length > 0);
    }];

   
    RACSignal *birthdayValidSignal = [RACObserve(self, birthDate) map:^id _Nullable(NSDate *date) {
        return @(date != nil);
    }];
     [[RACSignal combineLatest:@[nickValidSignal, birthdayValidSignal, RACObserve(self.famaleBtn, selected), RACObserve(self.maleBtn, selected)]
                      reduce:^id(NSNumber *nickValid, NSNumber *birthdayValid, NSNumber *femaleSelected, NSNumber *maleSelected) {
        return @(nickValid.boolValue && birthdayValid.boolValue && (femaleSelected.boolValue || maleSelected.boolValue));
    }]
     subscribeNext:^(NSNumber * _Nullable isEnabled) {
        @strongify(self);
        self.doneBtn.enabled = isEnabled.boolValue;
    }];
    

}

- (void)doneAction{
    [USFeedbackTool notifySuccess];

    
    NSString *nickname = self.nickTx.text;

    NSInteger sex = 1;
    if (self.famaleBtn.selected) {
        sex = 0;
    }
    NSTimeInterval timestamp = [self.birthDate timeIntervalSince1970];
    NSString *birthday = [NSString stringWithFormat:@"%li",(NSInteger)timestamp];
 
    [self startLoading];
    NSDictionary *params = @{@"nickname":nickname,
                             @"sex":@(sex),
                             @"birthday":birthday};

    [[EMNetWork shareManager] em_post:API_EditUser
                               params:params
                                  hud:nil
                           showError:YES
                              success:^(EMApiModel *api) {
        [self.view endEditing:YES];
        
        if (!api.success) {
            [self loadingFailed];
            return;
        }
        USUser *user = [USUser user];
        user.nickname = nickname;
        user.sex = sex;
        user.birthday = birthday;
        
        [USUser saveUser:user];

        [self loadingSuccess];
        
        UIWindowScene *scene = (UIWindowScene *)[UIApplication sharedApplication].connectedScenes.allObjects.firstObject;
        
        SceneDelegate *sceneDelegate = (SceneDelegate *)scene.delegate;
        
        [sceneDelegate switchToMainInterface];
    } fail:^{
        
        [self loadingFailed];
        
    }];
}


- (void)editWithIndex:(NSInteger)index {
    if (index != 0) {
        [self.nickTx resignFirstResponder];
    }
    
    if (index == 0) {
        self.nickBgView.layer.borderColor = UIColor.brightBorderColor.CGColor;
        self.sexBgView.layer.borderColor = UIColor.clearColor.CGColor;
        self.birthdayBgView.layer.borderColor = UIColor.clearColor.CGColor;
    }else if (index == 1) {
        self.nickBgView.layer.borderColor = UIColor.clearColor.CGColor;
        self.sexBgView.layer.borderColor = UIColor.brightBorderColor.CGColor;
        self.birthdayBgView.layer.borderColor = UIColor.clearColor.CGColor;
    }else if (index == 2) {
        self.nickBgView.layer.borderColor = UIColor.clearColor.CGColor;
        self.sexBgView.layer.borderColor = UIColor.clearColor.CGColor;
        self.birthdayBgView.layer.borderColor = UIColor.brightBorderColor.CGColor;
    }
}
- (void)keyboardWillShow:(NSNotification *)notification {
  
    [self editWithIndex:0];

}

- (IBAction)chooseMale:(id)sender {
    self.maleBtn.selected = YES;
    self.famaleBtn.selected = NO;

    [self editWithIndex:1];

}

- (IBAction)chooseFamale:(id)sender {
    self.maleBtn.selected = NO;
    self.famaleBtn.selected = YES;
    
    [self editWithIndex:1];
}

- (IBAction)chooseBirthdayAction:(id)sender {
    [self editWithIndex:2];

    USDateAlertView *alert = [[USDateAlertView alloc]initWithDate:[NSDate date] andSubTitle:@"设置您的生日日期" limitToNow:YES];
    [alert showInView:UIViewController.topViewController.view];
    @weakify(self)
    alert.didChooseBlock = ^(NSDate * _Nonnull date) {
        @strongify(self)
        self.birthDate = date;
        NSString * dateString = [NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle];
        [self.birthdayBtn setTitleColor:UIColor.titleColor forState:0];
        [self.birthdayBtn setTitle:dateString forState:0];
    };
}

- (UIButton *)doneBtn {
    if (_doneBtn == nil) {
        _doneBtn = [UIButton us_fillButtonWithTitle:@"开始"];
        _doneBtn.layer.cornerRadius = 14;
        [_doneBtn addTarget:self action:@selector(doneAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _doneBtn;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
